#include "ffmpegprogress.h"

FFmpegProgress::FFmpegProgress(QWidget *parent): QProgressBar(parent),
    rotateAngle(0),
    m_persent(0),
    msDelay(100)
{
    myTimer = new QTimer(this);
    connect(myTimer, SIGNAL(timeout()), this, SLOT(process()));
    connect(this, SIGNAL(destroyed()), this, SLOT(closeFile()));
}

void FFmpegProgress::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);
    rotateAngle = 360*m_persent/100;
    int side = qMin(width(), height());
    QRectF outRect(0, 0, side, side);
    QRectF inRect(20, 20, side-40, side-40);
    QString valueStr = QString("%1%").arg(QString::number(m_persent));
    //画外圆
    p.setPen(Qt::NoPen);
    p.setBrush(QBrush(QColor("#ddd9d9")));
    p.drawEllipse(outRect);
    p.setBrush(QBrush(QColor("#85d57b")));
    p.drawPie(outRect, (90-rotateAngle)*16, rotateAngle*16);
    //画遮罩
    p.setBrush(palette().window().color());
    p.drawEllipse(inRect);
    //画文字
    QFont f = QFont("Microsoft YaHei", 15, QFont::Bold);
    p.setFont(f);
    p.setFont(f);
    p.setPen(QColor("#555555"));
    p.drawText(inRect, Qt::AlignCenter, valueStr);
}

/**
 * @brief FFmpegProgress::setPersent 设置进度值 0~100
 * @param persent 设置值 0~100
 */
void FFmpegProgress::setPersent(int persent)
{
    if(persent != m_persent)
    {
        m_persent = persent;
        update();
    }
}

/**
 * @brief FFmpegProgress::updateFilePath 更新ffmpeg的进度文件路径
 * @param f 文件路径
 */
void FFmpegProgress::updateFilePath(QString f)
{
    stopProcess();
    if(filePath != "")
    {
        closeFile();
    }
    filePath = f;
    file = new QFile(filePath);
    file->open(QIODevice::ReadOnly | QIODevice::Text);
    fileStream = new QTextStream(file);
    startProcess();
}

/**
 * @brief FFmpegProgress::startProcess 定时器开始工作
 */
void FFmpegProgress::startProcess()
{
    myTimer->start(msDelay);
}

/**
 * @brief FFmpegProgress::stopProcess 定时器停止工作
 */
void FFmpegProgress::stopProcess()
{
    myTimer->stop();
}

/**
 * @brief FFmpegProgress::setInterval 设置定时器间隔
 * @param ms 毫秒
 */
void FFmpegProgress::setInterval(int ms)
{
    msDelay = ms;
    if(myTimer->isActive())
    {
        myTimer->setInterval(msDelay);
    }
}

/**
 * @brief FFmpegProgress::closeFile 关闭文件流
 */
void FFmpegProgress::closeFile()
{
    qDebug() << "关闭文件>>" + filePath;
    file->close();
}

/**
 * @brief FFmpegProgress::process 定时器溢出后执行的方法
 */
void FFmpegProgress::process()
{
    if(filePath != "" && file->isOpen())
    {
        QString line = fileStream->readLine();
        if(line != "")
        {
            if(line.contains("progress=end"))
            {
                emit onFinish();
            }
            if(line.contains("total_size="))
            {
                QString temp = line.mid(11, line.length() - 1);
                emit inProcess(temp.toLongLong());
            }
        }
    }
}
